package com.jemmyee.pizza.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.jemmyee.core.dao.Page;
import com.jemmyee.pizza.entity.Apply;
import com.jemmyee.pizza.entity.ApplyComment;
import com.jemmyee.pizza.entity.ApplyFlow;
import com.jemmyee.pizza.entity.Buckle;
import com.jemmyee.pizza.entity.CustomAddress;
import com.jemmyee.pizza.entity.Equi;
import com.jemmyee.pizza.entity.EquiRegister;
import com.jemmyee.pizza.entity.Prepaid;
import com.jemmyee.pizza.entity.PrepaidVip;
import com.jemmyee.pizza.entity.Role;
import com.jemmyee.pizza.entity.Task;
import com.jemmyee.pizza.entity.User;
import com.jemmyee.pizza.service.IApplyCommentService;
import com.jemmyee.pizza.service.IApplyFlowService;
import com.jemmyee.pizza.service.IApplyService;
import com.jemmyee.pizza.service.IBuckleService;
import com.jemmyee.pizza.service.ICustomAddressService;
import com.jemmyee.pizza.service.IEquiRegisterService;
import com.jemmyee.pizza.service.IEquiService;
import com.jemmyee.pizza.service.IPrepaidService;
import com.jemmyee.pizza.service.IPrepaidVipService;
import com.jemmyee.pizza.service.IRoleService;
import com.jemmyee.pizza.service.ITaskService;
import com.jemmyee.pizza.service.IUserService;
import com.jemmyee.pizza.web.Constants;

@Controller
@RequestMapping("/admin/apply")
public class ApplyController {

	private static final Log log = LogFactory.getLog(ApplyController.class);
	
	@Autowired
	private IApplyService<Apply> applyService ;
	@Autowired
	private IEquiService<Equi> equiService ;
	@Autowired
	private IEquiRegisterService<EquiRegister> equiRegisterService ;
	@Autowired
	private ITaskService<Task> taskService ;
	@Autowired
	private IApplyFlowService<ApplyFlow> applyFlowService ;
	@Autowired
	private IApplyCommentService<ApplyComment> applyCommentService ;
	@Autowired
	private IRoleService<Role> roleService ;
	//private IDeptService<Dept> deptService ;
	@Autowired
	private IUserService<User> userService;
	@Autowired
	private ICustomAddressService<CustomAddress> customAddressService ;
	@Autowired
	private IBuckleService<Buckle> buckleService ;
	@Autowired
	private IPrepaidService<Prepaid> prepaidService ;
	@Autowired
	private IPrepaidVipService<PrepaidVip> prepaidVipService ;
	
	/**
	 * 
	 * @param index
	 * @param from
	 * @param apply
	 * @param viewType 0待办、1已办、2已完结
	 * @param request
	 * @return
	 */
	@RequestMapping("/apply_list/{from}/{index}")
	public ModelAndView applyList(@PathVariable Integer index,@PathVariable String from,Apply apply,Integer viewType,HttpServletRequest request){
		
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/admin/apply/apply_list");
		
		
		User currentUser = this.getCurrentUser((String)request.getSession().getAttribute(Constants.ONLINE_ADMIN)) ;

		if(currentUser != null && currentUser.getRoleIDS() != null && !"".equals(currentUser.getRoleIDS())){
			
			String limit = currentUser.getRoleIDS().replace("_", ",") ;
			if(limit.indexOf(",") == 0)limit = limit.substring(1);
			if(limit.lastIndexOf(",") == (limit.length() - 1))limit = limit.substring(0,limit.length() -1) ;
			
			List<ApplyFlow> flows = applyFlowService.findByLimit(new String[]{"roleId in (" + limit + ")"}, null) ;
			
			Integer[] limit_status = new Integer[flows.size()] ;
			for(int i = 0 ; i < flows.size() ; i++){
				limit_status[i] = flows.get(i).getStatus() ;
			}
			
			if(flows != null && flows.size() > 0){
				
				
				
				Apply applyBean = new Apply() ;
				Integer startIndex = 0;
				
				if ("form".equals(from)) {
					applyBean = apply;
					request.getSession().setAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN, applyBean);
				}else if ("page".equals(from)) {
					if (request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN) != null) {
						applyBean = (Apply) request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
					}
					//startIndex = index ;
					if(index == -1 && request.getSession().getAttribute("session_page_sys_startIndex") != null){
						startIndex = (Integer)request.getSession().getAttribute("session_page_sys_startIndex") ;
					}
					if(index != -1){
						startIndex = index ;
						request.getSession().setAttribute("session_page_sys_startIndex", index);
					}
				}else if ("init".equals(from)) {
					request.getSession().removeAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
					request.getSession().removeAttribute("session_page_sys_startIndex");
				}
				
				
				
				DetachedCriteria dc = DetachedCriteria.forClass(Apply.class);
				
				if(viewType == null || viewType == 0){
					if(applyBean != null && applyBean.getStatus() != null){
						dc.add(Restrictions.eq("status", applyBean.getStatus())) ;
					}else{
						dc.add(Restrictions.in("status", limit_status)) ;
					}
				}else if(viewType == 1){
					String sql = "SELECT apply_id FROM apply_flow_comments where user_name = '"+currentUser.getName()+"' GROUP BY apply_id" ;
					List<List<String>> results = applyService.queryByJDBC(sql, 1) ;
					
					if(results != null && results.size() > 0){
						Integer [] applyIds = new Integer[results.size()] ;
						for(int i = 0 ; i < results.size() ; i++){
							applyIds[i] = Integer.parseInt(results.get(i).get(0)) ;
						}
						dc.add(Restrictions.in("applyId", applyIds)) ;
					}else{
						dc.add(Restrictions.eq("applyId", -1)) ;
					}
				}else if(viewType == 2){
					dc.add(Restrictions.eq("status", 8)) ;
				}
				
				if(applyBean != null && applyBean.getCustomName() != null && !"".equals(applyBean.getCustomName())){
					dc.add(Restrictions.like("customName", applyBean.getCustomName(), MatchMode.ANYWHERE)) ;
				}
				
				if(applyBean != null && applyBean.getCardId() != null && !"".equals(applyBean.getCardId())){
					dc.add(Restrictions.eq("cardId", applyBean.getCardId())) ;
				}
				
				if(applyBean != null && applyBean.getShenqingDate() != null){
					dc.add(Restrictions.eq("shenqingDate", applyBean.getShenqingDate())) ;
				}
				
				if(applyBean != null && applyBean.getAddress() != null && !"".equals(applyBean.getAddress())){
					dc.add(Restrictions.eq("address", applyBean.getAddress())) ;
				}
				
				
				
				Page page = applyService.findPageByCriteria(dc, Constants.DEFAULT_PAGESIZE, startIndex,null);
				
				for(Object a : page.getItems()){
					Apply tmp = (Apply)a ;
					ApplyFlow af = applyFlowService.findByProperty("status", tmp.getStatus()).get(0);
					
					tmp.setStatusView(af.getInfo());
					
					if(this.reProcessAble(this.preFlow(null, af), limit_status))tmp.setReProcessAble(1) ;
					if(this.processAble(tmp.getStatus(), limit_status))tmp.setProcessAble(1);
					if(af.getNextStatus() != null || af.getPreStatus() != null || af.getRefStatus() != null)tmp.setChangeAble(1);
					if(af.getAbleEdit() != null && af.getAbleEdit() == 1)tmp.setEditAble(1);
				}
				
				List<ApplyFlow> results = applyFlowService.findByProperty("needEqui", 1) ;
				if(results != null && results.size() > 0){
					mv.addObject("needEquiFlow", results.get(0));
				}
				
				mv.addObject("applyBean", applyBean);
				mv.addObject("flows", flows);
				mv.addObject("viewType", viewType);
				mv.addObject("page",page);
			}
			
		}
		return mv ;
	}
	
	@RequestMapping("/apply_address_group")
	public ModelAndView applyAddressGroup(String address){
		ModelAndView mv=new ModelAndView();
		
		String sql = "" ;
		if(address != null && !"".equals(address)){
			sql = "SELECT address,COUNT(address) FROM apply WHERE status < 7 and address like '%"+address+"%' GROUP BY address" ;
		}else{
			sql = "SELECT address,COUNT(address) FROM apply WHERE status < 7 and address IS NOT NULL GROUP BY address" ;
		}
		
		List<List<String>> applyAddressGroups = applyService.queryByJDBC(sql, 2);
		
		mv.addObject("applyAddressGroups",applyAddressGroups) ;
		mv.setViewName("/admin/apply/apply_address_group") ;
		return mv ;
	}
	
	@RequestMapping("/apply_info/{id}")
	public ModelAndView applyInfo(@PathVariable Integer id){
		ModelAndView mv=new ModelAndView();
		
		Apply apply = applyService.findById(id) ;
		
		ApplyFlow applyFlow = applyFlowService.findByProperty("status", apply.getStatus()).get(0);
		
		List<ApplyComment> applyComments = applyCommentService.findByLimit(new String[]{"applyId = " + id}, "fromStatus");
		
		List<ApplyComment> next_applyComments = null ;
		List<ApplyComment> pre_applyComments = null ;
		List<ApplyComment> ref_applyComments = null ;
		List<ApplyComment> added_applyComments = null ;
		
		for(ApplyComment ac : applyComments){
			if(ac.getProcessType() == 0 || ac.getProcessType() == 3){
				if(next_applyComments == null)next_applyComments = new ArrayList<ApplyComment>();
				next_applyComments.add(ac) ;
			}
			if(ac.getProcessType() == 1){
				if(pre_applyComments == null)pre_applyComments = new ArrayList<ApplyComment>();
				pre_applyComments.add(ac) ;
			}
			if(ac.getProcessType() == 2){
				if(ref_applyComments == null)ref_applyComments = new ArrayList<ApplyComment>();
				ref_applyComments.add(ac) ;
			}
			if(ac.getProcessType() == 4){
				if(added_applyComments == null)added_applyComments = new ArrayList<ApplyComment>();
				added_applyComments.add(ac) ;
			}
			
		}
		
		
		mv.addObject("apply", apply) ;
		mv.addObject("applyFlow", applyFlow);
		mv.addObject("next_applyComments", next_applyComments) ;
		mv.addObject("pre_applyComments", pre_applyComments) ;
		mv.addObject("ref_applyComments", ref_applyComments) ;
		mv.addObject("added_applyComments", added_applyComments) ;
		
		mv.setViewName("/admin/apply/apply_info") ;
		
		return mv ;
	}
	
	@RequestMapping("/apply_to_mod/{modType}/{id}")
	public ModelAndView applyToMod(@PathVariable String modType,@PathVariable Integer id){
		ModelAndView mv=new ModelAndView();

		Apply apply = null ;
		if("update".equals(modType)){
			apply = applyService.findById(id) ;
		}else{
			apply = new Apply() ;
		}
		
		mv.addObject("apply",apply);
		mv.addObject("modType",modType) ;
		
		mv.setViewName("/admin/apply/apply_mod");
		
		return mv ;
	}
	
	@RequestMapping("/apply_mod/{modType}")
	public ModelAndView applyMod(@PathVariable String modType,@ModelAttribute Apply apply,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		
		if("update".equals(modType)){
			applyService.update(apply) ;
		}else{
			apply.setShenqingDate(new Date());
			apply.setShouliJingban((String)request.getSession().getAttribute(Constants.ONLINE_ADMIN)) ;
//			if(apply.getCustomType() == 2){
//				apply.setStatus(6);
//			}else{
				apply.setStatus(1);
//			}
			applyService.save(apply) ;
		}
		
		mv.addObject("location", "admin/apply/apply_list/page/-1");
		mv.setViewName("/admin/apply/redirect") ;
		
		return mv  ;

	}
	
	@RequestMapping("/apply_to_process/{id}")
	public ModelAndView applyToProcess(@PathVariable Integer id){
		ModelAndView mv=new ModelAndView();
		
		Apply apply = applyService.findById(id) ;
		
		ApplyFlow applyFlow = applyFlowService.findByProperty("status", apply.getStatus()).get(0);
		
		List<ApplyFlow> remainFlows = null; 
		
		remainFlows = this.remainFlow(remainFlows, applyFlow);

		List<ApplyComment> applyComments = applyCommentService.findByLimit(new String[]{"applyId = " + id}, "fromStatus");
		
		List<ApplyComment> next_applyComments = null ;
		List<ApplyComment> pre_applyComments = null ;
		List<ApplyComment> ref_applyComments = null ;
		List<ApplyComment> added_applyComments = null ;
		
		for(ApplyComment ac : applyComments){
			if(ac.getProcessType() == 0 || ac.getProcessType() == 3){
				if(next_applyComments == null)next_applyComments = new ArrayList<ApplyComment>();
				next_applyComments.add(ac) ;
			}
			if(ac.getProcessType() == 1){
				if(pre_applyComments == null)pre_applyComments = new ArrayList<ApplyComment>();
				pre_applyComments.add(ac) ;
			}
			if(ac.getProcessType() == 2){
				if(ref_applyComments == null)ref_applyComments = new ArrayList<ApplyComment>();
				ref_applyComments.add(ac) ;
			}
			if(ac.getProcessType() == 4){
				if(added_applyComments == null)added_applyComments = new ArrayList<ApplyComment>();
				added_applyComments.add(ac) ;
			}
		}
		
		
		mv.addObject("apply", apply);
		mv.addObject("applyFlow", applyFlow) ;
		mv.addObject("remainFlows",remainFlows);
		mv.addObject("next_applyComments", next_applyComments) ;
		mv.addObject("pre_applyComments", pre_applyComments) ;
		mv.addObject("ref_applyComments", ref_applyComments) ;
		mv.addObject("added_applyComments", added_applyComments) ;
		mv.setViewName("/admin/apply/apply_process");
		
		return mv  ;
	}
	
	@RequestMapping("/apply_process/{processType}")
	public ModelAndView applyProcess(@PathVariable Integer processType,ApplyComment applyComment,Integer flyStatus,Integer payType,Double price,Apply applyBean,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		
		Apply apply = applyService.findById(applyComment.getApplyId());
		ApplyFlow applyFlow = applyFlowService.findByProperty("status", apply.getStatus()).get(0);
//		Dept dept = deptService.findById(applyFlow.getDeptId()) ;
		
		if(processType == 0 || processType == 3){
			if(apply.getStatus() == 3){
				apply.setInitPayType(payType);
				apply.setInitPrice(price);
			}else if(apply.getStatus() == 6){
				apply.setOpenPayType(payType) ;
				apply.setOpenPrice(price) ;
			//}else if(apply.getStatus() == 6){
				apply.setMeterName(applyBean.getMeterName()) ;
				apply.setMeterType(applyBean.getMeterType()) ;
				if(apply.getMeterType() == 0){
					
					if(apply.getCustomType() == 2){
						PrepaidVip prepaidVip = new PrepaidVip(apply.getApplyId(),
								apply.getCustomName(),apply.getCustomType()==2?"商业用气":"居民用气",2.43,
								/*apply.getMeterTypeView()*/null,apply.getTelNo(),apply.getAddress() + apply.getAddressExtend(),
								apply.getShenqingDate(),apply.getShenqingJingban(),null,"123456",
								null,null,null,
								null,null,null,
								null,null,null,null,apply.getMeterName()
								);
						prepaidVipService.save(prepaidVip) ;
					}else{
						Prepaid prepaid = new Prepaid(apply.getApplyId(),
								apply.getCustomName(),apply.getCustomType()==2?"商业用气":"居民用气",2.43,
								/*apply.getMeterTypeView()*/null,apply.getTelNo(),apply.getAddress() + apply.getAddressExtend(),
								apply.getShenqingDate(),apply.getShenqingJingban(),null,"123456",
								null,null,null,
								null,null,null,
								null,null,null,null,apply.getMeterName()
								);
						prepaidService.save(prepaid) ;
					}
				}else if(apply.getMeterType() == 1){
					Buckle buckle = new Buckle(apply.getApplyId(),
							apply.getCustomName(),apply.getAddress() + apply.getAddressExtend(),null,
							apply.getTelNo(),null,null,
							apply.getCustomTypeView(),"123456",apply.getShenqingDate(),
							apply.getShenqingJingban(),null,apply.getMeterName()) ;
					buckleService.save(buckle) ;
				}
			}
		}
		
		if(processType == 1){
			apply.setStatus(applyFlow.getPreStatus()) ;
		}else if(processType == 2){
			apply.setStatus(applyFlow.getRefStatus()) ;
		}else if(processType == 3){
			apply.setStatus(flyStatus) ;
		}else{
			apply.setStatus(applyFlow.getNextStatus()) ;
		}
		System.out.println(processType);
		applyService.update(apply) ;
		
		applyComment.setProcessComments(applyComment.getProcessComments().replace("\r\n", "<br>"));
		if(applyComment.getProcessComments() == null || "".equals(applyComment.getProcessComments())){
			applyComment.setProcessComments("无");
		}
		
//		applyComment.setDeptName(dept.getName()) ;
		applyComment.setUserName((String)request.getSession().getAttribute(Constants.ONLINE_USERNAME)) ;
		
		applyComment.setFromStatus(applyFlow.getStatus()) ;
		applyComment.setToStatus(apply.getStatus()) ;
		applyComment.setProcessType(processType) ;
		applyComment.setFromInfo(applyFlow.getInfo());
		applyComment.setToInfo(applyFlowService.findByProperty("status", apply.getStatus()).get(0).getInfo());
		applyCommentService.save(applyComment);
		

		mv.addObject("location", "admin/apply/apply_list/page/-1");
		mv.setViewName("/admin/apply/redirect") ;
		
		return mv ;
	}
	
	@RequestMapping("/apply_to_comment/{id}")
	public ModelAndView applyToComment(HttpServletRequest request,@PathVariable Integer id){
		
		ModelAndView mv=new ModelAndView();
		
		User currentUser = this.getCurrentUser((String)request.getSession().getAttribute(Constants.ONLINE_ADMIN)) ;

		if(currentUser != null && currentUser.getRoleIDS() != null && !"".equals(currentUser.getRoleIDS())){
			
			String limit = currentUser.getRoleIDS().replace("_", ",") ;
			if(limit.indexOf(",") == 0)limit = limit.substring(1);
			if(limit.lastIndexOf(",") == (limit.length() - 1))limit = limit.substring(0,limit.length() -1) ;
			
			List<ApplyFlow> flows = applyFlowService.findByLimit(new String[]{"roleId in (" + limit + ")"}, null) ;
			Integer[] limit_status = new Integer[flows.size()] ;
			for(int i = 0 ; i < flows.size() ; i++){
				limit_status[i] = flows.get(i).getStatus() ;
			}
			
			if(flows != null && flows.size() > 0){
				
				Apply apply = applyService.findById(id) ;
				
				ApplyFlow applyFlow = applyFlowService.findByProperty("status", apply.getStatus()).get(0);
				
				List<ApplyFlow> reProcessFlows = new ArrayList<ApplyFlow>() ;
				
				List<ApplyFlow> preFlows = null ;
				preFlows = this.preFlow(preFlows, applyFlow) ;
				
				for(ApplyFlow preFlow : preFlows){
					for(Integer s : limit_status){
						if(s.intValue() == preFlow.getStatus().intValue()){
							reProcessFlows.add(preFlow) ;
							break ;
						}
					}
				}
				
				List<ApplyComment> applyComments = applyCommentService.findByLimit(new String[]{"applyId = " + id}, "fromStatus");
				
				List<ApplyComment> next_applyComments = null ;
				List<ApplyComment> pre_applyComments = null ;
				List<ApplyComment> ref_applyComments = null ;
				List<ApplyComment> added_applyComments = null ;
				
				for(ApplyComment ac : applyComments){
					if(ac.getProcessType() == 0 || ac.getProcessType() == 3){
						if(next_applyComments == null)next_applyComments = new ArrayList<ApplyComment>();
						next_applyComments.add(ac) ;
					}
					if(ac.getProcessType() == 1){
						if(pre_applyComments == null)pre_applyComments = new ArrayList<ApplyComment>();
						pre_applyComments.add(ac) ;
					}
					if(ac.getProcessType() == 2){
						if(ref_applyComments == null)ref_applyComments = new ArrayList<ApplyComment>();
						ref_applyComments.add(ac) ;
					}
					if(ac.getProcessType() == 4){
						if(added_applyComments == null)added_applyComments = new ArrayList<ApplyComment>();
						added_applyComments.add(ac) ;
					}
				}
				
				
				
				mv.addObject("apply", apply);
				mv.addObject("reProcessFlows", reProcessFlows);

				mv.addObject("next_applyComments", next_applyComments) ;
				mv.addObject("pre_applyComments", pre_applyComments) ;
				mv.addObject("ref_applyComments", ref_applyComments) ;
				mv.addObject("added_applyComments", added_applyComments) ;
				mv.setViewName("/admin/apply/apply_comment");
			}
		}
		
		return mv ;
	}
	
	@RequestMapping("/apply_comment")
	public ModelAndView applyComment(ApplyComment applyComment,Integer flowId,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		
		ApplyFlow applyFlow = applyFlowService.findById(flowId) ;
		
		applyComment.setProcessComments(applyComment.getProcessComments().replace("\r\n", "<br>"));
		if(applyComment.getProcessComments() == null || "".equals(applyComment.getProcessComments())){
			applyComment.setProcessComments("无");
		}
		
//		applyComment.setDeptName(dept.getName()) ;
		applyComment.setUserName((String)request.getSession().getAttribute(Constants.ONLINE_USERNAME)) ;
		
		applyComment.setFromStatus(applyFlow.getStatus()) ;
		applyComment.setToStatus(applyFlow.getStatus()) ;
		applyComment.setFromInfo(applyFlow.getInfo());
		applyComment.setProcessType(4) ;
		
		applyCommentService.save(applyComment);
		

		mv.addObject("location", "admin/apply/apply_list/page/-1");
		mv.setViewName("/admin/apply/redirect") ;
		
		return mv ;
	}
	
	@RequestMapping("/apply_for_select/{index}")
	public ModelAndView applyForSelect(@PathVariable Integer index){
		ModelAndView mv=new ModelAndView();
		
		List<ApplyFlow> results = applyFlowService.findByProperty("needTask", 1) ;
		
		if(results != null && results.size() > 0){
		
			DetachedCriteria dc = DetachedCriteria.forClass(Apply.class);
			
			dc.add(Restrictions.eq("status", results.get(0).getStatus()));
			
			Page page = applyService.findPageByCriteria(dc, Constants.DEFAULT_PAGESIZE, index,null);
			
			mv.addObject("page", page) ;
			
		}

		mv.setViewName("/admin/apply/apply_for_select");
		return mv ;
	}
	
	
	@RequestMapping("/address_list/{from}/{index}")
	public ModelAndView addressList(@PathVariable Integer index,@PathVariable String from,CustomAddress address,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		
		CustomAddress addressBean = new CustomAddress() ;
		Integer startIndex = 0;
		
		if ("form".equals(from)) {
			addressBean = address;
			request.getSession().setAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN, addressBean);
		}else if ("page".equals(from)) {
			if (request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN) != null) {
				addressBean = (CustomAddress) request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
			}
			//startIndex = index ;
			if(index == -1 && request.getSession().getAttribute("session_page_sys_startIndex") != null){
				startIndex = (Integer)request.getSession().getAttribute("session_page_sys_startIndex") ;
			}
			if(index != -1){
				startIndex = index ;
				request.getSession().setAttribute("session_page_sys_startIndex", index);
			}
		}else if ("init".equals(from)) {
			request.getSession().removeAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
			request.getSession().removeAttribute("session_page_sys_startIndex");
		}
		
		DetachedCriteria dc = DetachedCriteria.forClass(CustomAddress.class);
		
		Page page = customAddressService.findPageByCriteria(dc, Constants.DEFAULT_PAGESIZE, startIndex,null);
		
		mv.addObject("page",page);
		mv.setViewName("/admin/apply/address_list");
		
		return mv ;
	}
	
	@RequestMapping("/address_for_select/{index}")
	public ModelAndView addressForSelect(@PathVariable Integer index,CustomAddress address){
		ModelAndView mv=new ModelAndView();
		
		DetachedCriteria dc = DetachedCriteria.forClass(CustomAddress.class);
		
		Page page = customAddressService.findPageByCriteria(dc, Constants.DEFAULT_PAGESIZE, index,null);
		
		mv.addObject("page",page);
		mv.setViewName("/admin/apply/address_for_select");
		
		return mv ;
	}

	@RequestMapping("/address_to_mod/{modType}/{id}")
	public ModelAndView addressToMod(@PathVariable String modType,@PathVariable Integer id){
		ModelAndView mv=new ModelAndView();
		
		CustomAddress address = null ;
		if("update".equals(modType)){
			address = customAddressService.findById(id) ;
		}else{
			address = new CustomAddress() ;
		}
		
		mv.addObject("address",address) ;
		mv.addObject("modType", modType) ;
		
		
		mv.setViewName("/admin/apply/address_mod");
		return mv ;
	}
	
	@RequestMapping("/address_mod/{modType}")
	public ModelAndView addressMod(@PathVariable String modType,CustomAddress address){
		ModelAndView mv=new ModelAndView();
		if("update".equals(modType)){
			customAddressService.update(address) ;
		}else{
			customAddressService.save(address) ;
		}
		mv.addObject("location", "admin/apply/address_list/page/-1");
		mv.setViewName("/admin/apply/redirect") ;
		
				
		return mv ;
	}
	@RequestMapping("/address_del/{id}")
	public ModelAndView addressDel(@PathVariable Integer id){
		ModelAndView mv=new ModelAndView();
		
		CustomAddress address = customAddressService.findById(id) ;
		customAddressService.delete(address) ;
		
		mv.addObject("location", "admin/apply/address_list/page/-1");
		mv.setViewName("/admin/apply/redirect") ;
		
		return mv ;
	}
	
	
	@RequestMapping("/task_list/{from}/{index}")
	public ModelAndView taskList(@PathVariable Integer index,@PathVariable String from,@ModelAttribute Task task,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		
		Task taskBean = new Task() ;
		Integer startIndex = 0 ;
		
		if ("form".equals(from)) {
			taskBean = task;
			request.getSession().setAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN, taskBean);
		}else if ("page".equals(from)) {
			if (request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN) != null) {
				taskBean = (Task) request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
			}
			startIndex = index ;
			if(startIndex == 0 && request.getSession().getAttribute("session_page_sys_startIndex") != null){
				startIndex = (Integer)request.getSession().getAttribute("session_page_sys_startIndex") ;
			}
			if(index != 0){
				request.getSession().setAttribute("session_page_sys_startIndex", index);
			}
		}else if ("init".equals(from)) {
			request.getSession().removeAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
			request.getSession().removeAttribute("session_page_sys_startIndex");
		}
		
		DetachedCriteria dc = DetachedCriteria.forClass(Task.class);
		
		Page page = taskService.findPageByCriteria(dc, Constants.DEFAULT_PAGESIZE, startIndex,null);
		
		mv.addObject("page",page);
		mv.setViewName("/admin/apply/task_list");
		
		return mv ;
	}
	
	@RequestMapping("/task_to_mod/{modType}/{id}")
	public ModelAndView taskToMod(@PathVariable String modType,@PathVariable Integer id){
		ModelAndView mv=new ModelAndView();
		
		Task task = null ;
		List<Apply> applys = new ArrayList<Apply>() ;
		if("update".equals(modType)){
			task = taskService.findById(id) ;
			
			
			if(task.getApplyIds() != null && !"".equals(task.getApplyIds())){
				for(String applyId : task.getApplyIds().split(",")){
					applys.add(applyService.findById(Integer.parseInt(applyId)));
				}
			}
			
		}else{
			task = new Task() ;
		}
		
		
		mv.addObject("task", task) ;
		mv.addObject("applys",applys);
		mv.addObject("modType",modType) ;
		mv.setViewName("/admin/apply/task_mod");
		
		return mv ;
	}
	
	@RequestMapping("/task_mod/{modType}")
	public ModelAndView taskMod(@PathVariable String modType,Task task){
		ModelAndView mv=new ModelAndView();
		
		if("update".equals(modType)){
			taskService.update(task) ;
		}else{
			taskService.save(task) ;
		}
		
		mv.addObject("location", "admin/apply/task_list/page/0");
		mv.setViewName("/admin/apply/redirect") ;
		
		return mv ;
	}
	
	@RequestMapping("/to_register_equi/{applyId}")
	public ModelAndView toRegisterEqui(@PathVariable Integer applyId){
		ModelAndView mv=new ModelAndView();
		
		EquiRegister er = null ;
		
		Apply apply = applyService.findById(applyId);
		List<EquiRegister> ers = equiRegisterService.findByProperty("applyId", applyId) ;
		List<Equi> equis = null ;
		String[] curYearParts = null ;
		String[] nextYearParts = null ;
		
		
		if(ers != null && ers.size() > 0){
			er = ers.get(0) ;
			equis = equiService.findByProperty("equipmentId", er.getId());
			if(er.getCurYearPart() != null && !"".equals(er.getCurYearPart())){
				curYearParts = er.getCurYearPart().split(",");
			}
			if(er.getNextYearPart() != null && !"".equals(er.getNextYearPart())){
				nextYearParts = er.getNextYearPart().split(",") ;
			}
		}else{
			er = new EquiRegister() ;
			er.setApplyId(applyId);
			equis = new ArrayList<Equi>() ;
		}
		
		mv.addObject("apply",apply);
		mv.addObject("er",er);
		mv.addObject("equis", equis);
		mv.addObject("curYearParts",curYearParts);
		mv.addObject("nextYearParts",nextYearParts);
		mv.setViewName("/admin/apply/equi_register");
		
		
		return mv ;
	}
	
	@RequestMapping("/register_equi")
	public ModelAndView registerEqui(EquiRegister equiRegister,String[] curYearParts,String[] nextYearParts,
			String[] equiName,String[] specification,Integer[] amount,String[] heatLoad,String[] pressure,String[] connType,String[] portSize){
		ModelAndView mv=new ModelAndView();
		
		if(equiRegister != null){
			if(equiRegister.getId() != null){
				equiRegisterService.update(equiRegister);
				List<Equi> equis = equiService.findByProperty("equipmentId", equiRegister.getId()) ;
				equiService.deleteAll(equis);
			}else{
				equiRegisterService.save(equiRegister);
			}
			if(equiName != null){
				for(int i = 0 ; i < equiName.length ; i++){
					Equi equi = new Equi() ;
					equi.setEquipmentId(equiRegister.getId());
					equi.setEquiName(equiName[i]);
					equi.setSpecification(specification[i]);
					equi.setAmount(amount[i]);
					equi.setHeatLoad(heatLoad[i]);
					equi.setPressure(pressure[i]);
					equi.setConnType(connType[i]);
					equi.setPortSize(portSize[i]);
					
					equiService.save(equi);
				}
			}
			
		}
		mv.addObject("location", "admin/apply/apply_list/page/-1");
		mv.setViewName("/admin/apply/redirect") ;
		
		return mv ;
	}
	
	@RequestMapping("/flow_to_mod")
	public ModelAndView flowToMod(){
		ModelAndView mv=new ModelAndView();
		
		List<ApplyFlow> applyFlows = applyFlowService.findByLimit(null, "status");
		
		List<Role> roles = roleService.findAll() ;
//		List<Dept> depts = deptService.findAll() ;
		
		mv.addObject("applyFlows",applyFlows);
		
		mv.addObject("roles",roles);
//		mv.addObject("depts",depts);
		
		mv.setViewName("/admin/apply/flow_mod");
		
		return mv ;
	}
	
	@RequestMapping("/flow_mod")
	public ModelAndView flowMod(Integer[] status,Integer[] roleId,String[] info,Integer[] nextStatus,Integer[] preStatus,Integer[] refStatus,Integer needEqui,Integer needTask,String ableEdit){
		ModelAndView mv=new ModelAndView();
		
		List<ApplyFlow> applyFlows = applyFlowService.findAll() ;
		applyFlowService.deleteAll(applyFlows);
		
		
		if(status != null && status.length > 0){
			for(int i = 0 ; i < status.length ; i++){
				Integer tmp_needEqui = (needEqui.intValue() == status[i].intValue()) ? 1 : 0 ;
				Integer tmp_needTask = (needTask.intValue() == status[i].intValue()) ? 1 : 0 ;
				
				Integer tmp_ableEdit = 0 ;
				if(ableEdit != null && !"".equals(ableEdit)){
					String[] ables = ableEdit.split(",");
					for(String able : ables){
						if(able.equals(String.valueOf(status[i]))){
							tmp_ableEdit = 1 ;
							break ;
						}
					}
				}
				
				ApplyFlow af = new ApplyFlow(status[i],roleId[i],info[i],nextStatus[i],preStatus[i],refStatus[i],tmp_needEqui,tmp_needTask,tmp_ableEdit) ;
				applyFlowService.save(af);
			}
		}
		
		

		mv.addObject("location", "admin/apply/flow_to_mod");
		mv.setViewName("/admin/apply/redirect") ;
		
		return mv ;
	}
	
	@RequestMapping("/apply_inquiry")
	public ModelAndView applyInquiry(Integer inquiryType,Integer dateType,String startDate,String endDate){
		
		ModelAndView mv=new ModelAndView();
		
		if(inquiryType != null){
		
			List<List<String>> result = applyService.inquiry(inquiryType, dateType, startDate,endDate);
			
			mv.addObject("result", result);
			mv.addObject("inquiryType",inquiryType) ;
			mv.addObject("dateType", dateType) ;
			mv.addObject("startDate", startDate) ;
			mv.addObject("endDate", endDate) ;
			mv.setViewName("/admin/apply/apply_inquiry") ;
			
		}
		
		return mv ;
		
	}
	
	
	
	
	
	
	
	public List<ApplyFlow> remainFlow(List<ApplyFlow> flows,ApplyFlow applyFlow){
		
		if(applyFlow != null && applyFlow.getNextStatus() != null){
			List<ApplyFlow> result = applyFlowService.findByProperty("status", applyFlow.getNextStatus()) ;
			if(result != null && result.size() > 0){
				if(flows == null)flows = new ArrayList<ApplyFlow>() ;
				flows.add(result.get(0));
				remainFlow(flows,result.get(0));
			}
		}
		
		return flows ;
	}
	
	public List<ApplyFlow> preFlow(List<ApplyFlow> flows,ApplyFlow applyFlow){
		if(applyFlow != null && applyFlow.getPreStatus() != null){
			List<ApplyFlow> result = applyFlowService.findByProperty("status", applyFlow.getPreStatus()) ;
			if(result != null && result.size() > 0){
				if(flows == null)flows = new ArrayList<ApplyFlow>() ;
				flows.add(result.get(0));
				preFlow(flows,result.get(0));
			}
		}
		return flows ;
	}
	
	public boolean reProcessAble(List<ApplyFlow> flows,Integer [] limit_status){
		if(flows == null || flows.size() == 0)return false ;
		if(limit_status == null || limit_status.length == 0)return false ;
		for(ApplyFlow flow : flows){
			for(Integer status : limit_status){
				if(flow.getStatus().intValue() == status.intValue())return true ;
			}
		}
		
		return false ;
	}
	
	public boolean processAble(Integer status,Integer [] limit_status){
		if(limit_status == null || limit_status.length == 0)return false ;
		for(Integer s : limit_status){
			if(s.intValue() == status.intValue())return true ;
		}
		return false ;
	}
	
	public User getCurrentUser(String username){
		
		if(username != null && !"".equals(username)){
			List<User> users=userService.findByProperty("name",username);
			if(users != null && users.size() > 0){
				return users.get(0);
			}
		}
		return null ;
	}
	
	public boolean contain(Object [] os,Object s){
		for(Object o : os){
			if(o.equals(s))return true ;
		}
		return false ;
	}
		
}
